<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\model;


use think\db\Query;
use think\facade\Db;
use think\model\concern\SoftDelete;

class AgentBillTemporary extends \think\Model
{
    use SoftDelete;
    protected $autoWriteTimestamp = 'datetime';
    protected $globalScope = ['userId'];

    public function getStatusTextAttr($value,$data){
        $status = $data['status'];
        $array = [
            0 => '未结算',
            1 => '已结算',
            3 => '已退款'
        ];
        return $array[$status];
    }

    public static function stepsAgent(array $array) : array{
        $agent1 = array_unique(array_column($array,'agent1'));
        $agent2 = array_unique(array_column($array,'agent2'));
        $agent3 = array_unique(array_column($array,'agent3'));
        $array = array_merge($agent1,$agent2,$agent3);
        $array = Db::name('agent')
            ->alias('a')
            ->field('a.id AS agent_id,u.nickname,u.picurl')
            ->where('a.id','in',$array)
            ->join('user u','a.user_id=u.id','left')
            ->select()
            ->toArray();
        $user = [];
        foreach ($array AS $key => $value)
            $user[$value['agent_id']] = $value;
        return $user;
    }

    public function commodityNameMaster(){
        return $this->hasOne(Commodity::class,'id','commodity_id')
            ->bind(['name','master']);
    }

    public function orderAgentProfit(){
        return $this->hasOne(OrderAgentProfit::class,'uniqid','uniqid')
            ->bind(['agent1','agent2','agent3','amount1','amount2','amount3']);
    }

    public function getStepsAttr($value,&$data) : int{
        for ($i = $value + 1;$i <= 3;$i++){
            if ($value == 0)break;
            $data['amount'.$i] = 0;
            $data['agent'.$i] = 0;
        }
        return $value;
    }

    public function sourceUserNicknamePicurl(){
        return $this->hasOne(User::class,'id','source_user_id')
            ->bind(['nickname','picurl']);
    }
}